<template>
  <div class="container">
    <div class="text-center upload-box">
      <div>
        <el-upload 
          ref="rebateUpload"
          class="upload-demo"
          drag
          :action="upload"
          name="excel"
          :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          v-show="isShowUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">{{$t('page.drop')}}，<em>{{$t('page.click')}}</em></div>
        </el-upload>
        <div class="reset-back"
            v-if="isShowStepOne">
          <div class="link"
              @click="changLogData">{{$t('page.modData')}}</div>
          <span class="link"
                @click="handleRemove">{{$t('page.emptyData')}}</span>
        </div>
        <div class="upload-name-box">
          <div>
            <div class="upload-name"
                v-show="isShowUploadtxt">
              {{uploadFile.name}}
              <el-button type='text' @click="handleRemove()">x</el-button>
            </div>
            <el-progress 
              :percentage="percentage"
              color="#e6a23c"
              v-show="isShowPer"
            ></el-progress>
          </div>
          <el-select 
            v-if="formulaValue === 1" 
            style="margin-left:20px;" 
            v-model="formulaItem" 
            @change="selectChange"
            placeholder="请选择公式">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>

    <el-tabs @tab-click="handleClick" type="border-card" v-show="isShowStepOne" v-model="activeName">
      <el-tab-pane v-for="item in tabList" :key="item.uuid" :name="item.uuid">
        <div class="tab_color" slot="label">
          <i class="color_piece" :style="{background: item.color}"></i>
          <span class="text_piece"> {{ item.lable }}</span>
        </div>
        <DetailItem
          v-if="item.uuid === activeName"
          v-loading.fullscreen.lock="pageLoading" 
          :ItemData="itemData"
          :uuidC="item.uuid"
        ></DetailItem>
      </el-tab-pane>
    </el-tabs>

    <el-dialog  
      :visible.sync="isShowInputLog"
      :close-on-click-modal="false"
      width="90%"
      top="5%"
      center>
      <div>
        <!-- 公式选择 -->
        <div class="space space-unit">
          <div class="space-title">{{$t('page.formula')}}：</div>
          <el-radio-group v-model="formulaValue">
            <el-radio :label="0">{{$t('page.default')}}</el-radio>
            <el-radio :label="1">{{$t('page.newFormula')}}</el-radio>
          </el-radio-group>
          <el-select 
            v-if="formulaValue === 1" 
            style="margin-left:20px;" 
            v-model="formulaItem" 
            placeholder="请选择公式">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <!-- 浓度类型选择 -->
        <div class="space space-unit">
          <div class="space-title">{{$t('page.label')}}{{$t('public.type')}}：</div>
          <el-radio-group v-model="mmolType">
            <el-radio :label="0">{{$t('page.quality')}}{{$t('page.label')}}</el-radio>
            <el-radio :label="1">{{$t('page.Moore')}}{{$t('page.label')}}</el-radio>
          </el-radio-group>
        </div>
        <!-- 单位 -->
        <div class="space space-unit" v-if="mmolType === 0">
          <div class="space-title">{{$t('page.unit')}}：</div>
          <el-radio-group v-model="unit">
            <el-radio 
              :label="v"
              v-for="v,i in unitOption"
              :key="i">
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 摩尔单位 -->
        <div class="space space-unit" v-if="mmolType === 1">
          <div class="space-title">{{$t('page.unit')}}：</div>
          <el-radio-group v-model="mass">
            <el-radio label="M">M</el-radio>
          </el-radio-group>
        </div>

        <!-- 选择颜色 -->
        <holeColors ref="myHoleColors" :fillInHole="waveName"></holeColors>


        <div class="space-btn">
          <el-button 
            type="primary"
            @click="handleCompute()"
            size="small"
            :loading="computeLoading"
            class="btn-submit-color">
              {{$t('page.submit')}}
          </el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { fetchAffinitytwomany, fetchTwomanyStepB } from '@/api/table'
import { setStore, getStore } from '@/utils/common'
import { getToken } from '@/utils/auth'
import holeColors from '../components/holeColors.vue'
import DetailItem from '../components/detail.vue'

export default {
  data() {
    return {
      originalData: [],
      computeLoading: false, //  提交按钮-loading
      isShowInputLog: false, // 提交弹窗显示
      isShowStepOne: false, // 显示结果页
      lang: getStore('spr-lang') || 'zh', // 语言类型
      isShowUpload: true, // 上传文件组件
      isShowUploadtxt: false,  // 文件名字
      uploadFile: {},   // 上传的文件
      unitOption: ['pg/ml', 'ng/ml', 'μg/ml', 'mg/ml'],  // 单位选项
      unit: 'μg/ml',     // 单位
      mole: '115207373',
      isShowPer: false,
      percentage: 0,
      // allStepOneCharts: [],
      isRepeatSubmit: false,
      waveName: [], // 弹窗浓度key值
      beforeLable: [], // 浓度数据值
      // baseStepOne: [],   // 图片列表
      paramResult: [],
      dissociation: [],
      zero: '0',   // 是否归零
      formulaValue: 0, // 公式选择
      filledList: [],  // 已填写的浓度孔号
      checkList: ['曲线', '拟合'], 
      smoothList: [],  // 大表格数据
      standby:[], // 备用数据
      moleValue: [], // 摩尔浓度
      mmolType: 1, // 浓度类型
      mass: 'M',
      fitting: 0, // 拟合优化选择
      formulaItem: null, // 新公式
      histogramList: {},
      imgUrl: '',
      // 公式的选项
      options: [
        {
          name: 'b + a*( exp(c*x)-1 )/c',
          value: 1
        },
        {
          name: 'a*exp(-x/c) + b',
          value: 2
        },
        {
          name: 'a+exp(c*x)',
          value: 3
        },
        {
          name: 'c - exp(-a*x)',
          value: 4
        },
        {
          name: 'b+a*exp(c*x)',
          value: 5
        }
      ],
      itemData: {},
      tabList: [],
      pageLoading: false,
      activeName: ''
    }
  },
  components: {
    holeColors,
    DetailItem
  },
  methods: {
    switchChange(value) {
      this.isRepeatSubmit = true
      this.zero = value
      this.handleCompute()
    },

    selectChange(value) {
      this.isRepeatSubmit = true
      this.formulaItem = value
      this.handleCompute()
    },
    
    changLogData() {
      this.checkList = ['曲线', '拟合']
      this.isRepeatSubmit = true
      this.isShowInputLog = true
    },
    beforeUpload(file) {
      this.uploadFile = file
      this.isShowPer = true
      this.isShowUpload = false
      this.isShowUploadtxt = true
      this.percentage += 60 + Math.floor(Math.random() * 10)
    },
    handleSuccess(file, filelist) {
      // file = {
      const next = 100 - this.percentage
      this.percentage += next
      setTimeout(() => {
        this.isShowPer = false
      }, 1000)
      if (file.status === 200) {
        this.waveName = file.data.hole
        this.moleValue = this.waveName.map(() => [])
        this.isShowInputLog = true

        setStore('auuid_submit', file.data.uuid)
      } 
    },
    handleError(err) {
      this.$message.error(err)
    },
    async handleCompute() {
      if(!this.$refs.myHoleColors.valueList.length || !this.$refs.myHoleColors.formList.length) {
        return this.$message.warning('浓度未填写或未选组！')
      }
      const isMole = this.mmolType === 0 && this.$refs.myHoleColors.formList.some(item => !item.mole)
      if(isMole) {
        return this.$message.warning('请填写分子量！')
      }
        const requestData = {
          uuid: getStore('auuid_submit'),
          unit: this.mmolType === 1 ? 'M' : this.unit,
          formulas: this.formulaValue === 0 ? 0 : this.formulaItem,
          quality: this.mmolType,
          crpValue: this.$refs.myHoleColors.valueList,
          wtsonDtoList: this.$refs.myHoleColors.formList
        }
        this.computeLoading = true
        try {
          let info = await fetchAffinitytwomany(requestData)
          if (info.status === 200) {
            this.tabList = info.data.result
            setStore('auuid', info.data.uuid)
            
            this.getItemData(info.data.result[0].uuid)
            this.activeName = info.data.result[0].uuid
  
            this.isShowInputLog = false
            this.isShowStepOne = true
          } else {
            this.$message.error(info.msg)
          }
        } finally {
          this.computeLoading = false
        }
    },

    handleClick(tab, event) {
      this.getItemData(this.activeName)
    },

    // 获取结果页页面信息
    async getItemData(uuid_c) {
      this.pageLoading = true
      try {
        const res = await fetchTwomanyStepB({
          uuid: getStore('auuid'),
          uuid_c,
        })
        const obj = {
          originalData: res.data.originalData,
          // imgUrl: res.data.avg5_map['imgPath'] || '',
          paramResult: res.data.result_data_excel,
          // histogramList: res.data.originalData_start[0],
          lineData: res.data.originalData_hl_merge[0],
          hole: res.data.hole,
          fittingData: res.data.originalData_hl_merge_fitting[0],
          concentration: res.data.computeCrpValue.value,
          mole: res.data.mole || '',
          uuid: res.data.uuid,
          dissociation: res.data.dissociation || [],
        }
        this.itemData = obj
        if(res.status !== 200) {
          return this.$message.error(res.data.msg || "服务器繁忙！请稍后再试")
        }
      } catch(err) {
        return err
      } finally {
        this.pageLoading = false
      }
    },

    handleRemove() {
      this.$refs['rebateUpload'].clearFiles() //清除文件
      //上传框
      this.isShowUpload = true
      this.isShowUploadtxt = false
      //可以计算
      // this.computeAllowed = true
      this.computeLoading = false
      //上传进度条
      this.percentage = 0
      //显示进度
      this.isShowPer = false
      this.paramResult = []
      this.originalData = []
      this.isShowStepOne = false
      this.isShowInputLog = false
      this.unit = 'μg/ml'
    },
  },
  computed: {
    upload: () => {
      return `${process.env.BASE_URL}affinitytwomany/affinity/upload/step1`
    },
    headerUpload: () => {
      const data = {}
      data.TOKEN = getToken()
      if (localStorage.getItem('spr-lang') === 'en') {
        data.LANG = 'ENG' // 传语言
      }
      return data
    },
  },
}
</script>

<style lang="scss" scoped>
.space {
  display: flex;
  align-items: center;
  margin: 0;
  overflow: hidden;
  margin-bottom: 20px;
  .space-title {
    min-width: 120px;
    display: flex;
    justify-content: flex-end;
    align-items: center
  }
  .space-title::before {
    content: '*';
    color: red;
    margin-right: 2px;
  }
}
.space-unit {
  margin-bottom: 20px;
}
.space-btn {
  margin-top: 30px;
  margin-left: 400px;
}
.reset-back {
  display: flex;
  align-items: center;
  margin: 0 20px 20px;
  .link {
    cursor: pointer;
    color: #409eff;
    font-style: normal;
    margin-right: 20px;
  }
}
.tab_color {
  display: flex;
  align-items: center;
  .color_piece {
    display: inline-block;
    width: 18px;
    height: 18px;
    margin-right: 6px;
  }
  .text_piece {
    display: inline-block;
    width: 100px;
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>